import React, { Component } from 'react';
import ReactNative from 'react-native';
import { connect } from 'react-redux';
import {
  ScrollView,
  View,
  TextInput,
  Image,
  TouchableHighlight,
  StyleSheet,
  Text,
  Button
} from 'react-native';

class Home extends Component {
  constructor(props){
    super(props);
    this.state = { searching: false, ingredientsInput: '' };
  }
  
  searchPressed() {
    this.setState({searching:true});
    this.props.fetchRecipes(this.state.ingredientsInput).then( () => {
      this.setState({ searching:false });
    });
  }

  recipes(){
    let resData = Object.keys(this.props.searchedRecipes).map( key => this.props.searchedRecipes[key]);
    
    return resData;
  }

  render(){
    return <View style={styles.scene}>
      <Button
          title='About'
          onPress={ () => this.props.screenProps.setRoute('About') }
      />
      <View style={styles.searchSection}>
      <TextInput style={styles.searchInput}
        returnKeyType="search"
        placeholder="Ingredients (comma delimited)"
        onChangeText={(ingredientsInput) => this.setState({ingredientsInput})}
        value={this.state.ingredientsInput}
      />
          <TouchableHighlight onPress= { () => this.searchPressed()} style={styles.searchButton}>
          <Text>
            Fetch Recipes2
          </Text>
          </TouchableHighlight>
      </View>
      <ScrollView style={styles.scrollSection}>
        {!this.state.searching && this.recipes().map((recipe) => {
          return <View key={recipe.href}>
            <Image source={ { uri: recipe.thumbnail} } style={styles.resultImage} />
            <Text style={styles.resultText}>{recipe.title}</Text>
          </View>
        })}
        {this.state.searching ? <Text>Searching...</Text> : null }
      </ScrollView>
    </View>
  }
}
const styles = StyleSheet.create({
  scene:{
    flex:1,
    marginTop: 20,
    backgroundColor: '#ecf0f1',
  },
  searchSection:{
    height: 40,
    borderBottomColor: '#000',
    borderBottomWidth: 1,
    padding: 1,
    flexDirection: 'row'
  },
  searchInput:{
    flex: 0.7
  },
  searchButton:{
    paddingTop:8,
    flex: 0.3
  },
  scrollSection:{
    flex: 0.8,
  },
  resultImage:{
    height: 150,
  },
  resultText:{
    backgroundColor: '#000',
    color: '#FFF',
    height: 20
  }
});
function mapStateToProps(state){
  return {
    searchedRecipes: state.searchedRecipes
  }
}
export default connect(mapStateToProps)(Home);
